package config

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"ytdownloader-api/models"
)

type DbConfig struct {
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
	Charset  string `yaml:"charset"`
	Prefix   string `yaml:"prefix"`
}

type AppConfig struct {
	Host string `yaml:"host"`
	Port string `yaml:"port"`
}

type Config struct {
	App      AppConfig `yaml:"app"`
	Database DbConfig  `yaml:"database"`
}

var db *gorm.DB
var cfg *Config

func getDsn() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local", cfg.Database.User, cfg.Database.Password, cfg.Database.Host, cfg.Database.Port, cfg.Database.Database, cfg.Database.Charset)
}

func migrate() error {
	return db.AutoMigrate(&models.VideoRecord{})
}

func InitDB() error {
	opened, err := gorm.Open(mysql.Open(getDsn()), &gorm.Config{})
	if err != nil {
		return err
	}
	db = opened
	return migrate()
}

func GetDB() *gorm.DB {
	return db
}

func InitConfig() error {
	var data = Config{}
	parsed := viper.New()
	parsed.SetConfigName("config")
	parsed.AddConfigPath(".")
	parsed.SetConfigType("yaml")
	if err := parsed.ReadInConfig(); err != nil {
		return err
	}
	if err := parsed.Unmarshal(&data); err != nil {
		return err
	}
	cfg = &data
	return nil
}

func GetConfig() *Config {
	return cfg
}
